/*
下载用工具
参数1 下载地址
参数2 存放地址
*/
package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"time"

	"github.com/cavaliercoder/grab"
)

func main() {
	fmt.Println("下载网络文件到本地文件夹")
	paramlist := os.Args
	paramSize := len(paramlist)
	if paramSize != 3 {
		if paramSize == 2 {
			var params [2]string
			for n, p := range paramlist {
				params[n] = p
				fmt.Println("n = ", n, ";param = ", params[n])
			}
			time.Sleep(time.Duration(2) * time.Second) // sleep 2 second
			//cmd := exec.Command("cmd.exe", "/c", "start "+params[1]) // 这种反而会因为路径带空格导致异常
			cmd := exec.Command("cmd.exe", "/c", params[1])
			err := cmd.Run()
			if err != nil {
				log.Println("启动失败:", err)
			} else {
				log.Println("启动成功!")
			}
		}
		return
	}
	var params [3]string
	for n, p := range paramlist {
		params[n] = p
		fmt.Println("n = ", n, ";param = ", params[n])
	}
	client := grab.NewClient()
	req, _ := grab.NewRequest(params[2], params[1])
	//req, _ := grab.NewRequest("C:/Users/Administrator/go/src/gitee.com/xuanwuyan/go-download-windows", "https://statichz.qiuhui.com/avatar/e16b0ac4-1677-4595-8aee-b7e5a6a15d94.exe")
	// start download
	//fmt.Printf("Downloading %v...\n", req.URL())
ReDownload:
	resp := client.Do(req)
	//fmt.Printf("  %v\n", resp.HTTPResponse.Status)

	// start UI loop
	t := time.NewTicker(500 * time.Millisecond)
	defer t.Stop()
	const timeMax = 3
	timeIndex := 0
Loop:
	for {
		select {
		case <-t.C:
			fmt.Printf("%v#%v##\n",
				resp.BytesComplete(),
				resp.Size())

		case <-resp.Done:
			// download is complete
			break Loop
		}
	}

	// check for errors
	if err := resp.Err(); err != nil {
		timeIndex++
		if timeMax == timeIndex {
			fmt.Printf("####\n")
			fmt.Fprintf(os.Stderr, "Download failed: %v\n", err)
			os.Exit(1)
			return
		} else {
			goto ReDownload // 循环下载 下载地址神了 各种异常循环就是下载不完整
		}
	}

	fmt.Printf("Download saved to %v \n", resp.Filename)

	/// 2 delete // 确实实时状态回传
	//ReDownload:
	//	resp, err := grab.Get(params[2], params[1])
	//	// unexpected EOF
	//	if err != nil {
	//		//log.Fatal(err)
	//		log.Println(err)
	//		goto ReDownload
	//	} else {
	//		fmt.Println("Download saved to", resp.Filename)
	//	}

	/// 1 delete // 下载地址问题有点多 http经常断开
	// res, err := http.Get(params[1]) // 下载地址问题有点多 http经常断开
	// if err != nil {
	// 	panic(err)
	// }
	// file, err := os.Create(params[2])
	// if err != nil {
	// 	panic(err)
	// }
	// io.Copy(file, res.Body)
}
